<script>
export default {
  name: 'UserinfoPassword',
  data () {
    return {
      formData: {
        oldPassword: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '原密码不能为空' },
          {
            validator: (rule, value, callback) => {
              this.$axios.get('userinfo', {
                params: {
                  param: 'checkPwd',
                  password: value
                }
              }).then(() => {
                callback()
              }).catch(() => {
                callback(new Error('原密码不正确'))
              })
            }
          }
        ],
        password: [
          { required: true, message: '新密码不能为空' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码' },
          {
            validator: (rule, value, callback) => {
              if (value === this.formData.password) {
                callback()
              } else {
                callback(new Error('两次密码不一致'))
              }
            }
          }
        ]
      },
      show: false
    }
  },
  methods: {
    showDialog () {
      this.formData = { ...this.$options.data().formData }
      this.show = true
    },
    submit () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.$axios.post('userinfo?param=updatePwd', { password: this.formData.password }).then(() => {
            this.$alert('密码修改成功，请重新登录！', { type: 'success' }).then(() => {
              this.$cookies.remove('token')
              this.$router.replace('/')
            })
          }).catch(e => e)
        }
      })
    }
  }
}
</script>

<template>
  <el-dialog :visible.sync="show" v-if="show" title="修改密码">
    <el-form :model="formData" :rules="rules" ref="formData" label-width="80px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" show-password clearable placeholder="请输入原密码"/>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="formData.password" show-password clearable placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" show-password clearable placeholder="请再次输入新密码"/>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
